package com.xuecheng.auth.controller;

import com.xuecheng.api.auth.AuthControllerApi;
import com.xuecheng.auth.service.AuthService;
import com.xuecheng.framework.domain.ucenter.ext.AuthToken;
import com.xuecheng.framework.domain.ucenter.ext.UserToken;
import com.xuecheng.framework.domain.ucenter.request.LoginRequest;
import com.xuecheng.framework.domain.ucenter.response.AuthCode;
import com.xuecheng.framework.domain.ucenter.response.JwtResult;
import com.xuecheng.framework.domain.ucenter.response.LoginResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/")
public class AuthController implements AuthControllerApi {
    @Value("${auth.clientId}")
    String clientId;
    @Value("${auth.clientSecret}")
    String clientSecret;
    @Value("${auth.cookieDomain}")
    String cookieDomain;
    @Value("${auth.cookieMaxAge}")
    int cookieMaxAge;
    @Value("${auth.tokenValiditySeconds}")
    int tokenValiditySeconds;
    @Autowired
    private AuthService authService;


    //用户登录
    @Override
    @PostMapping("/userlogin")
    public LoginResult login(LoginRequest loginRequest,HttpServletResponse httpServletResponse) {
        //判断用户名是否输入
        if( loginRequest==null|| StringUtils.isEmpty(loginRequest.getUsername())){
            ExceptionCast.cast(AuthCode.AUTH_USERNAME_NONE);
        }
        //判断密码是否输入
        if(StringUtils.isEmpty(loginRequest.getPassword())){
            ExceptionCast.cast(AuthCode.AUTH_PASSWORD_NONE);
        }
      AuthToken authToken=authService.login(loginRequest.getUsername(),loginRequest.getPassword(),clientId,clientSecret);
        //将身份令牌写到cookie中
        String jti_token = authToken.getJti_token();
        CookieUtil.addCookie(httpServletResponse,cookieDomain,"/","uid",jti_token,cookieMaxAge,false);
        return new LoginResult(CommonCode.SUCCESS,jti_token);

    }
    //用户退出登录
    @Override
    @PostMapping("/userlogout")
    public ResponseResult logout(HttpServletRequest request,HttpServletResponse response) {
        //从cookie中获取身份令牌
        String uid = getTokenFormCookie(request);
        //从redis中删除令牌
        authService.delToken(uid);
        //删除cookie，将cookie的时间设为0即可
        CookieUtil.addCookie(response,cookieDomain,"/","uid",uid,0,false);

        return new ResponseResult(CommonCode.SUCCESS);
    }
    //获取userJwt令牌
    @Override
    @GetMapping("/userjwt")
    public JwtResult userJwt(HttpServletRequest request) {
        //获取cookie中的身份令牌
        String uid = getTokenFormCookie(request);
        if(uid==null){
            return new JwtResult(CommonCode.FAIL,null);
        }
        //拿到身份令牌从redis中查询令牌信息
       AuthToken authToken=authService.getUserToken(uid);
       //获取jwt令牌
        if(authToken!=null) {
            String jwt_token = authToken.getJwt_token();
            return new JwtResult(CommonCode.SUCCESS, jwt_token);
        }
        return null;
    }
    //从cookie中获取令牌
    public String getTokenFormCookie(HttpServletRequest request){
        Map<String, String> cookies = CookieUtil.readCookie(request, "uid");
        if(cookies!=null){
            String uid = cookies.get("uid");
            return uid;
        }
        return null;
    }
}
